<template>
	<view class="container">
		<view class="content">
			<map style="width: 100%; height: 200px;" :latitude="latitude" :longitude="longitude"
				:markers="covers"></map>
			<view class="name">
				<img src="@/static/image/img9.png" alt="">
				<text>济南西电特种变压器有限公司</text>
			</view>
			<view class="time">
				<text>签到时间</text>
				<text class="value">{{time}}</text>
			</view>
			<view class="address" @click="chooseLocation">
				<text class="addressLeft">签到地址</text>
				<text v-if="address" class="addressRight">{{address}}</text>
				<text v-if="!address" class="value">选择位置</text>
			</view>
			<!-- <view v-if="state==1" class="address">
				<text>签到地址</text>
				<text v-if="address">{{address}}</text>
				<text v-if="!address" class="value">选择位置</text>
			</view> -->
			<view class="time">
				<text>司机姓名</text>
				<text class="value">{{driverName}}</text>
			</view>
			<view class="time">
				<text>司机联系电话</text>
				<text class="value">{{driverPhone}}</text>
			</view>
			<view class="pic">
				<view class="uploadGroup">
					<view class="box" v-for="(item,index) in fileList" :key="index">
						<image :src="configUrl+item.filePath" alt="" mode="aspectFill" @click="clickImg(index)" />
						<view class="close" @click="closFun(index)">x</view>
					</view>
					<view class="box add" @click="addFlie">
						<image src="@/static/image/img10.png" alt="" mode="aspectFill" />
					</view>
				</view>
			</view>
		</view>
		<view style="padding: 0 10px 20px 10px;background-color: #fff;" v-if="isAuth ('activation:add')">
			<button type="primary" @click="submit()" :disabled="submitDisabled" style="margin-bottom: 20px;">激活</button>
		</view>
		<uni-popup ref="popup" type="dialog" background-color="#fff" style="width: 100%;">
			<view class="popup-content">
				<button type="primary" @click="getList">获取位置</button>
			</view>
		</uni-popup>
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog :type="msgType" cancelText="拒绝" confirmText="同意" title="提示" content="若不点击授权,将无法使用定位功能!"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import config from '@/config'
	import QQMapWX from "@/utils/qqmap-wx-jssdk.min.js"
	export default {
		data() {
			return {
				id: 0,
				title: '登录适配',
				latitude: 0,
				longitude: 0,
				latitude2: 0,
				longitude2: 0,
				covers: [],
				msgType: 'success',
				time: '',
				address: '',
				driverName: '',
				driverPhone: '',
				fileList: [],
				submitDisabled: false,
				configUrl: '',
				state: ''
			}
		},
		created() {
			this.init()
			this.configUrl = config.baseUrl
		},
		mounted() {
			// this.getList()
			// this.time = this.getDate()

		},
		
		methods: {
			openInfo() {
				this.$refs.popup.open()
			},
			dialogToggle() {
				this.$refs.alertDialog.open()
			},
			init() {
				this.getDrive()
				this.request({
					'url': '/wx/project/activate/info/' + this.$store.getters.productId,
					'method': 'get',
				}).then(res => {
					console.log(res)
					if (res && res.code == 200) {
						// this.list = res.info
						this.getDrive()
						this.getList()
						this.time = this.getDate()
						if (res.info) {
							this.state = 1
							this.latitude2 = res.info.lat
							this.longitude2 = res.info.lng
							// this.covers.push({
							// 	id: 1,
							// 	latitude: res.info.lat,
							// 	longitude: res.info.lng,
							// 	iconPath: '../../static/location.png',
							// 	width: '30px',
							// 	height: '30px'
							// })
							this.address = res.info.activateAddress
							this.time = res.info.activateTime
							// this.driverName = res.info.driverName
							// this.driverPhone = res.info.driverPhone
							this.id = res.info.id
							// appendixUrl: appendixUrl.toString(),
							// appendixName:appendixName.toString(),
							let data = []
							if (res.info.appendixName) {
								let appendixName = res.info.appendixName.split(',')
								let appendixUrl = res.info.appendixUrl.split(',')
								for (let i = 0; i < appendixName.length; i++) {
									data.push({
										fileName: appendixName[i],
										filePath: appendixUrl[i]
									})
								}
							}
							this.fileList = data

						} else {

						}
					}
				}).catch(err => {

				})
			},
			getDrive() {
				console.log(this.$store.getters.productId)
				this.request({
					'url': '/wx/project/info/' + this.$store.getters.productId,
					'method': 'get',
				}).then(res => {
					console.log(res)
					if (res && res.code == 200) {
						// this.list = res.info
						this.driverName = res.info.projectDrivers[0].driverName
						this.driverPhone = res.info.projectDrivers[0].driverPhone
					}
				}).catch(err => {

				})
			},
			getList() {
				uni.getLocation({
					type: 'gcj02',
					isHighAccuracy: true,
					success: (res) => {
						// let qqmapsdk = new QQMapWX({
						// 	key: 'HABBZ-4U3L5-OEQIJ-IB3MM-VF5F6-ZXFJP'
						// });
						this.latitude = res.latitude
						this.longitude = res.longitude
						this.covers.push({
							id: 1,
							latitude: res.latitude,
							longitude: res.longitude,
							iconPath: '../../static/location.png',
							width: '30px',
							height: '30px'
						})
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						// console.log(res);
						// this.address = re.result.address
						// qqmapsdk.reverseGeocoder({
						// 		location: {
						// 			latitude: res.latitude,
						// 			longitude: res.longitude
						// 		},
						// 		success: (re) => {
						// 			console.log(re.result, '详细地址信息'); //这里边就是你需要的定位数据了
						// 			this.address=re.result.address
						// 		},
						// 		fail: (re) => {
						// 			console.log(re, '失败信息');
						// 		},
						// 		})
					},
					fail(error) {
						// uni.showToast({
						//   title: '请勿频繁调用！',
						//   icon: 'none',
						// })
						console.log('失败', error)
					}

				});
			},
			chooseLocation() {
				uni.chooseLocation({
					type: 'wgs84',
					isHighAccuracy: true,
					success: (res) => {
						// let qqmapsdk = new QQMapWX({
						// 	key: 'HABBZ-4U3L5-OEQIJ-IB3MM-VF5F6-ZXFJP'
						// });
						if (Number(this.juli(this.latitude, this.longitude, res.latitude, res.longitude)) >
							0.5) {
							wx.showModal({
								title: '温馨提示',
								content: '位置不能离你大于500米',
								success: (res) => {
									if (res.confirm) {
										this.chooseLocation()
									} else if (res.cancel) {
										console.log('用户点击取消')
									}
								}
							});
						} else {
							this.latitude = res.latitude
							this.longitude = res.longitude
							this.latitude2 = res.latitude
							this.longitude2 = res.longitude
							this.covers.push({
								id: 1,
								latitude: res.latitude,
								longitude: res.longitude,
								iconPath: '../../static/location.png',
								width: '30px',
								height: '30px'
							})
							console.log('当前位置的经度：' + res.longitude);
							console.log('当前位置的纬度：' + res.latitude);
							console.log(res);
							this.address = res.address
						}


					},
					fail(error) {
						// uni.showToast({
						//   title: '请勿频繁调用！',
						//   icon: 'none',
						// })
						console.log('失败', error)
					}

				});
			},
			// 计算两地之间的距离
			juli(lat1, lng1, lat2, lng2) {
				console.log(lat1, lng1, lat2, lng2)
				var radLat1 = lat1 * Math.PI / 180.0;
				var radLat2 = lat2 * Math.PI / 180.0;
				var a = radLat1 - radLat2;
				var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math
					.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137;
				s = Math.round(s * 10000) / 10000;
				return s
			},
			dialogConfirm() {
				console.log('点击确认')
				this.getList()
			},

			dialogClose() {
				console.log('点击拒绝')
			},
			formatDate(year, month, day, hour, minute, seconds) {
				const newmonth = this.addZero(month);
				const newday = this.addZero(day);
				const newhour = this.addZero(hour);
				const newminute = this.addZero(minute);
				const newseconds = this.addZero(seconds);

				return year + '-' + newmonth + '-' + newday + ' ' + newhour + ":" + newminute + ":" +
					newseconds;
			},
			// 获取当前时间
			getDate(value) {
				let date = '';
				if (value) {
					date = new Date(value);
				} else {
					date = new Date();
				}
				const y = date.getFullYear(),
					m = date.getMonth() + 1,
					d = date.getDate(),
					h = date.getHours(), //获取当前小时数(0-23)
					f = date.getMinutes(),
					s = date.getSeconds();
				return this.formatDate(y, m, d, h, f, s);
			},
			addZero(num) {
				return Number(num) < 10 ? `0${num}` : num;
			},
			//选择本地图片
			addFlie() {
				if(this.fileList.length>=8){
					wx.showModal({
						title: '温馨提示',
						content: '图片不能超过8张',
						success: (res) => {
							return false
						}
					});
					return false
				}
				uni.chooseImage({
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					// sourceType: ['album'], //从相册选择
					count:8,
					success: (res) => {
						console.log(res);
						// let oldTem=this.fileList
						// let nsTem=[...oldTem,...res.tempFilePaths]
						// this.fileList=nsTem
						// console.log(this.fileList)
						let tempFilePaths = res.tempFilePaths
						tempFilePaths.forEach((tempFile) => {
							// console.log(tempFile.path, tempFile.name)
							uni.uploadFile({
								url: config.baseUrl + '/file/uploadFileInterface',
								filePath: tempFile, //接受的是数组
								name: 'file',
								method: "POST",
								header: {
									'token': this.$store.getters.token,
								},
								success: (uploadFileRes) => {
									//接口返回的数据
									let data = JSON.parse(uploadFileRes.data)
									// console.log(JSON.parse(uploadFileRes.data));
									this.fileList.push({
										id: data.map.id,
										fileName: data.map.fileName,
										filePath: data.map.filePath
									})

								},
								fail(err) {
									console.log(err);
								}
							});
						})
					}
				});
			},
			//删除
			closFun(e) {
				this.fileList.splice(e, 1)
			},
			//预览
			clickImg(index) {
				let list = this.fileList.map((item) => config.baseUrl + item.filePath)
				uni.previewImage({
					current: index,
					urls: list
				})
			},
			isAuth(key) {
				return JSON.parse(uni.getStorageSync('permissions') || '[]').indexOf(key) !== -1 || false
			},
			//提交
			submit() {
				this.submitDisabled = true
				let appendixUrl = []
				let appendixName = []
				console.log(this.fileList)
				if (!this.address) {
					uni.showToast({
						title: '请选择签到地址',
						icon: 'error'
					})
					this.submitDisabled = false
					return false
				}
				if (this.state == 1) {
					if (Number(this.juli(this.latitude, this.longitude, this.latitude2, this.longitude2)) > 0.5) {
						wx.showModal({
							content: '位置不能离你大于500米',
							showCancel: false, //是否显示取消按钮
							success: (res) => {
								if (res.cancel) {
									//点击取消,默认隐藏弹框
								} else {
									//点击确定
									this.submitDisabled = false
								}
							}
						});
						return false
					}
				}

				if (this.fileList.length) {
					for (let i = 0; i < this.fileList.length; i++) {
						appendixUrl.push(this.fileList[i].filePath)
						appendixName.push(this.fileList[i].fileName)
					}
				} else {
					uni.showToast({
						title: '激活文件不能为空',
						icon: 'error'
					})
					this.submitDisabled = false
					return false
				}
				//确认是否激活
				wx.showModal({
					content: '确认是否激活！',
					success: (res) => {
						if (res.cancel) {
							//点击取消,默认隐藏弹框
							this.submitDisabled = false
						} else {
							//点击确定
							this.request({
								'url': '/wx/project/activate',
								'method': 'post',
								'data': {
									appendixUrl: appendixUrl.toString(),
									appendixName: appendixName.toString(),
									activateAddress: this.address,
									activateTime: this.time,
									driverName: this.driverName,
									productId: this.$store.getters.productId,
									driverPhone: this.driverPhone,
									lat: this.latitude,
									lng: this.longitude,
									id: this.id ? this.id : undefined
								},

							}).then(res => {
								console.log(res)
								if (res && res.code == 200) {
									// this.list = res.info
									// this.valiFormData.productModel = res.info.model
									uni.showToast({
										title: '激活成功'
									})
									// this.submitDisabled = false
									// uni.navigateBack()
									setTimeout(() => {
										uni.$emit("getlist") //这里可以传个空,也可以传值过去
										uni.navigateBack()
										this.submitDisabled = false
									}, 1500)
								}
							}).catch(err => {
								this.submitDisabled = false
							})
						}
					}
				});

			}
		}
	}
</script>

<style>
	.container {
		/* background-color: #fff; */
	}

	.content {
		/* background-color: #fff; */
		/* border-radius: 10px;
		padding: 15px;
		box-shadow: 0px 0px 10px #e2dede; */
	}

	.content .uni-list-chat__header {
		width: 20px;
		height: 20px;
	}

	.content .uni-list-chat__content-title {
		font-size: 14px;
	}

	.content .uni-list-chat__content-title.uni-ellipsis {
		white-space: normal;
	}

	.content .uni-list--border-top {
		/* height: 0px!important; */
	}

	.uni-list-chat {
		border-bottom: 1px solid #f3eeee;
	}

	.name {
		display: flex;
		align-items: center;
		height: 50px;
		background-color: #fff;
		margin-bottom: 10px;
		padding: 0 10px;
		font-size: 16px;
	}

	.name img {
		width: 30px;
		height: 30px;
		margin-right: 10px;
	}

	.time,
	.address {
		display: flex;
		align-items: center;
		height: 50px;
		background-color: #fff;
		justify-content: space-between;
		margin-top: 3px;
		padding: 0 10px;
		font-size: 16px;
	}

	.addressLeft {
		min-width: 80px;
	}

	.addressRight {
		text-align: right;
	}

	.uploadGroup {
		display: flex;
		padding: 30rpx;
		flex-wrap: wrap;
	}

	.uploadGroup .box {
		width: 200rpx;
		height: 200rpx;
		background-color: #eee;
		margin-right: 15rpx;
		margin-bottom: 15rpx;
		position: relative;
	}

	.box image {
		width: 100%;
		height: 100%;
	}

	.add {
		font-size: 80px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #888;
	}

	.add image {
		width: 40%;
		height: 40%;
	}

	.pic {
		background-color: #fff;
	}

	.close {
		position: absolute;
		right: 0;
		top: 0;
		width: 50rpx;
		height: 50rpx;
		background-color: rgba(0, 0, 0, 0.7);
		color: #fff;
		border-radius: 0 0 0 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		padding-left: 12rpx;
		box-sizing: border-box;
		padding-bottom: 15rpx;
	}

	.value {
		color: #999;
		font-size: 14px;
	}
</style>